! This file is part of PanGu. All rights reserved.
module pangu_read

    use seakeeping_kinds, only: rk
    use seakeeping_error, only: file_read_error, file_not_found_error
    use seakeeping_filesystem, only: is_exist
    use seakeeping_string, only: to_string

contains

    !> 读入配置文件
    subroutine read_pangu_file(pangu_file, nstation, width, error)
        character(*), intent(in) :: pangu_file  !! 配置文件名
        integer, intent(out) :: nstation  !! 站点数
        real(rk), intent(out) :: width  !! 船宽
        character(:), allocatable, intent(out) :: error  !! 错误信息
        integer :: fid, istat
        character(128) :: imsg
        namelist /config/ nstation, width

        if (.not. is_exist(pangu_file)) then
            call file_not_found_error(error, pangu_file)
            return
        end if

        open (newunit=fid, file=pangu_file, action='read')
        read (fid, nml=config, iostat=istat, iomsg=imsg)
        if (istat /= 0) then
            call file_read_error(error, pangu_file, trim(imsg))
            close (fid)
            return
        end if

        close (fid)
    end subroutine read_pangu_file

    !> 读入数据文件
    subroutine read_data_file(data_file, data, nstation, message, error)
        character(*), intent(in) :: data_file  !! 数据文件名
        real(rk), dimension(nstation), intent(out) :: data  !! 数据：质量、外力
        integer, intent(in) :: nstation  !! 站点数
        character(*), intent(in) :: message  !! 信息
        character(:), allocatable, intent(out) :: error  !! 错误信息
        integer :: fid, i, istat
        character(128) :: imsg
        namelist /mass/ data
        namelist /pressure/ data

        if (.not. is_exist(data_file)) then
            call file_not_found_error(error, data_file)
            return
        end if

        open (newunit=fid, file=data_file, action='read')

        select case (message)
        case ('mass'); read (fid, nml=mass, iostat=istat, iomsg=imsg)
        case ('pressure'); read (fid, nml=pressure, iostat=istat, iomsg=imsg)
        end select
        if (istat /= 0) then
            call file_read_error(error, data_file, trim(imsg))
            close (fid)
            return
        end if

        close (fid)

    end subroutine read_data_file

end module pangu_read
